import { query, addResource, updateResource } from '@services/system/resource';

function dedupe(arr) {
  const result = [];
  let i;
  let j;
  const len = arr.length;
  for (i = 0; i < len; i++) {
    for (j = i + 1; j < len; j++) {
      if (arr[i].id === arr[j].id) {
        j = ++i;
      }
    }
    result.push(arr[i]);
  }
  return result;
}

export default {
  namespace: 'resource',

  state: {
    data: {
      list: [],
      pagination: {},
    },
    treeData: {},
  },

  effects: {
    *fetch(_, { call, put }) {
      const { data } = yield call(query, {});
      data.list = data.list.map(item => {
        return {
          key: item.permission_id,
          ...item,
        };
      });
      yield put({
        type: 'save',
        payload: data,
      });
    },
    *fetchTreeData(_, { call, put }) {
      let { data: { list } } = yield call(query, { page: 1, size: 1000 });
      list = list.map(el => {
        return {
          ...el,
          children: list.filter(item => item.id === el.id),
        };
      });
      list = dedupe(list);
      console.log('==========list=======', list);
      yield put({
        type: 'saveTreeData',
        payload: list,
      });
    },
    *add({ payload, callback }, { call, put }) {
      const { code } = yield call(addResource, { ...payload });
      if (code === 0) {
        const { data } = yield call(query, {});
        yield put({
          type: 'save',
          payload: data,
        });
      }
      if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const { code } = yield call(updateResource, { ...payload });
      if (code === 0) {
        const { data } = yield call(query, {});
        yield put({
          type: 'save',
          payload: data,
        });
      }
      if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    saveTreeData(state, action) {
      return {
        ...state,
        treeData: action.payload,
      };
    },
  },
};
